package com.daykw.xiaohongshu.util;

import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.daykw.xiaohongshu.model.TSessionId;

public class SessionUtils implements Runnable {
	private static Logger logger = Logger.getLogger(SessionUtils.class);
	private volatile boolean isRunning = true;
	private final int DEFAULT_RANGE_FOR_SLEEP = 10000*60*3;
	private volatile Map<Integer,TSessionId> map = new java.util.concurrent.ConcurrentHashMap<Integer,TSessionId>();
	private final Object lock = new Object();
	public static class Session{
		public static SessionUtils session;
		static {
			session = new SessionUtils();
			NutDao dao = SpringContextHolder.getBean("dao");
			List<TSessionId> list = dao.query(TSessionId.class,Cnd.where("status","=", 0).limit(1, 1000).orderBy("id", "desc"));
			for(TSessionId s : list) {
				session.map.put(s.getId(), s);
			}
			new Thread(session).start();
		}
	}
	
	private SessionUtils() {}
	
	public  TSessionId getQueue() {
		Random r = new Random();
		TSessionId s;
		synchronized(lock) {
			int size = map.keySet().size();
			s = map.get(map.keySet().toArray()[r.nextInt(size)]);
		}
		return s;
	}
	
	public void run() {
		NutDao dao = SpringContextHolder.getBean("dao");
		System.out.println("启动生产者线程！");
		try {
			while (isRunning) {
				logger.info("正在生产数据...");
				List<TSessionId> list = dao.query(TSessionId.class,Cnd.where("status","=", 0).limit(1, 1000).orderBy("id", "desc"));
				synchronized(lock) {
					Map<Integer,TSessionId> new_map = new java.util.concurrent.ConcurrentHashMap<Integer,TSessionId>();
					for(TSessionId s : list) {
						new_map.put(s.getId(), s);
					}
					map = new_map;
				}
				Thread.sleep(DEFAULT_RANGE_FOR_SLEEP);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			System.out.println("退出生产者线程！");
		}
	}
	
	
}
